//
//  WatchFaceMessage.m
//  uteped_sdk
//
//  Created by mateng on 2024/2/20.
//

#import "WatchFaceMessage.h"
#import "../utils/UIImage.h"
#import "../utils/WatchfaceFileDownloader.h"
#import "../utils/FileUtils.h"

#define SDK_KEY @"7b86304b4976bd8ef2368bc0a023bf48"

@implementation WatchFaceMessage

int watchFaceSecCount = 0;
int watchFaceSec = 29;

- (NSString *)getPath {
    return @"watchFace";
}

- (BOOL)methodCallConsumed:(NSString *)method params:(NSDictionary *)params result:(FlutterResult)result {
    __weak typeof(self)weakSelf = self;
    BOOL consumed = YES;

    if ([super methodCallConsumed:method params:params result:result])
        return YES;

    assert(method !=nil);

    BOOL connected = NO;
    if ([UTEBluetoothMgr sharedInstance].connnectModel != nil) {
        connected = [UTEBluetoothMgr sharedInstance].connnectModel.isConnected;
    }

    NSLog(@"is connected : %@", connected?@"YES":@"NO");
    if(!connected) {
        result(@NO);
        return NO;
    }

    if([method isEqualToString:@"getImageWatchFace"]) {
        NSLog(@"getImageWatchFace");
        if (![self isConnected]) {
            result(@"");
            return YES;
        }
        
        [[UTEDeviceMgr sharedInstance].dial getImageWatchFaceBlock:^(NSInteger errorCode, NSDictionary *uteDict) {
            NSLog(@"getImageWatchFace === %ld//%@", errorCode, uteDict);
            NSString *newtImageWatchFace = [weakSelf getNewDataString:uteDict];
            result(newtImageWatchFace);
        }];
    } else if([method isEqualToString:@"setImageWatchFace"]) {
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        NSDictionary *dictionay = [params objectForKey:KEY_VALUE];
        NSLog(@"applyWatchFace dictionay : %@", dictionay);
        NSString *positionIndex = [dictionay objectForKey:@"positionIndex"];
        NSString *index = [dictionay objectForKey:@"index"];
        NSString *name = [dictionay objectForKey:@"name"];
        
        UTEModelWatchFaceImage *watchFace = [[UTEModelWatchFaceImage alloc] init];
        watchFace.positionIndex = positionIndex.integerValue;
        watchFace.styleIndex = index.integerValue;

        [[UTEDeviceMgr sharedInstance].dial setImageWatchFaceModel:watchFace block:^(UTEModelWatchFaceImage *model, NSInteger errorCode, NSDictionary *uteDict) {
            result(errorCode == UTEDeviceErrorNil ? @YES : @NO);
        }];
    } else if([method isEqualToString:@"getWatchFaceOnlineInformation"]){
        NSLog(@"getWatchFaceOnlineInformation");
        
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        NSString *jsonString = [params objectForKey:KEY_VALUE];
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

        NSError *error = nil;
        id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

        if (error) {
            result(@NO);
        } else {
            NSDictionary *dictionary = (NSDictionary *)jsonObject;
//            NSString *languageType = dictionary[@"languageType"];
            NSString *refresh = dictionary[@"refresh"];
            NSNumber *height = dictionary[@"height"];
            NSNumber *width = dictionary[@"width"];
            NSNumber *maxCapacity = dictionary[@"maxCapacity"];
            NSNumber *shape = dictionary[@"shape"];
            NSNumber *cornerRadius = dictionary[@"cornerRadius"];

            if([refresh isEqualToString:@"true"]) {
                watchFaceSecCount = 0;
            }

            int start = watchFaceSec * watchFaceSecCount;
            UTEModelWatchServer *modelWatch = [[UTEModelWatchServer alloc] init];
            modelWatch.versionName = [UTEBluetoothMgr sharedInstance].connnectModel.versionName;
            modelWatch.address = [UTEBluetoothMgr sharedInstance].connnectModel.address;
            modelWatch.height = [height integerValue];
            modelWatch.width = [width integerValue];
            modelWatch.maxCapacity = [maxCapacity integerValue];
            modelWatch.cornerRadius = [cornerRadius integerValue];
            modelWatch.shape = [shape integerValue];
            modelWatch.startIndex = start;

            NSLog(@"getWatchFaceOnlineInformation===>> %@,%@,%ld", [UTEBluetoothMgr sharedInstance].connnectModel.versionName, [UTEBluetoothMgr sharedInstance].connnectModel.address, (long)[UTEBluetoothMgr sharedInstance].connnectModel.platform);

            [[UTEDeviceMgr sharedInstance].dial getWatchFromServer:(SDK_KEY) device:modelWatch success:^(NSArray<UTEModelWatchServer *> *success) {
                NSLog(@"getWatchFaceOnlineInformation success");
                if(success){
                    NSMutableArray *dictionaryArray = [NSMutableArray array];
                    for (UTEModelWatchServer *server in success) {
                        NSDictionary *serverDictionary = @{
                                @"id": [NSNumber numberWithInteger:server.ID],
                                @"title": server.title,
                                @"preview": [server.previewURLs objectAtIndex:0],
                                @"resource": server.firmwareURL,
                                @"firmwareSize": [NSNumber numberWithInteger:server.firmwareSize],
                                @"dowloadCount": [NSNumber numberWithInteger:server.dowloadCount],
                                @"type": [NSNumber numberWithInteger:server.type],
                                @"amount": [NSNumber numberWithInteger:server.amount],
                        };
                        [dictionaryArray addObject:serverDictionary];
                    }

                    NSDictionary *resultString = @{
                            @"flag":[NSNumber numberWithInt:1],
                            @"totalCount":dictionaryArray.lastObject[@"amount"],
                            @"watchFaceOnlineOneInfoList":dictionaryArray
                    };
                    NSData *resultData = [NSJSONSerialization dataWithJSONObject:resultString options:0 error:nil];
                    NSString *resultStr = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
                    NSLog(@"getWatchFaceOnlineInformation json %@", resultStr);
                    result(resultStr);
                } else {
                    result(@NO);
                }
            } failure:^(NSError *err) {
            NSLog(@"getWatchFaceOnlineInformation failure %@", err);
            result(@NO);
        }];
        }
    } else if([method isEqualToString:@"downloadFile"]){
        NSLog(@"downloadFile");
        
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        NSDictionary *dictionay = [params objectForKey:KEY_VALUE];
        NSLog(@"downloadFile dictionay: %@", dictionay);
        NSString *path = [dictionay objectForKey:KEY_PATH];
        NSString *fileURL = [dictionay objectForKey:@"url_path"];
        NSLog(@"downloadFile lastPathComponent: %@", [NSURL URLWithString:fileURL].lastPathComponent);

        NSString *fileName = [NSURL URLWithString:fileURL].lastPathComponent;
        NSString *filePath = [[path stringByAppendingString: @"/"] stringByAppendingString:fileName];

        if(filePath) {
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL success = [fileManager removeItemAtPath:filePath error:nil];
            NSLog(@"文件删除: %d//%@", success, filePath);
        }

        WatchfaceFileDownloader *fileDownloader = [[WatchfaceFileDownloader alloc] init];

        [fileDownloader startDownloadWithURL:[NSURL URLWithString:fileURL] toFileName:[NSURL URLWithString:fileURL].lastPathComponent progressHandler:^(float progress) {
            NSLog(@"Download progress: %f", progress);
        } completionHandler:^(NSURL *fileURL, NSError *error) {
            if (error) {
                NSLog(@"Download failed: %@", error.localizedDescription);
                result(@NO);
            } else {
                NSLog(@"File downloaded and saved at: %@", fileURL.path);
                result(@YES);
            }
        }];
    } else if([method isEqualToString:@"getServerWatchFace"]){
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        [[UTEDeviceMgr sharedInstance].dial getWatchFaceParams:^(UTEModelWatchFaceParams *model, NSInteger errorCode, NSDictionary *uteDict) {
            if (errorCode == UTEDeviceErrorNil) {
                UTEModelWatchServer *modelWatch = [[UTEModelWatchServer alloc] init];
                modelWatch.versionName = [UTEBluetoothMgr sharedInstance].connnectModel.versionName;
                modelWatch.address = [UTEBluetoothMgr sharedInstance].connnectModel.address;
                modelWatch.height = model.height;
                modelWatch.width = model.width;
                modelWatch.maxCapacity = model.maxCapacity;
                modelWatch.cornerRadius = model.cornerRadius;
                modelWatch.shape = model.shape;
                
                [[UTEDeviceMgr sharedInstance].dial getCustomWatchFromServer:SDK_KEY device:modelWatch success:^(NSArray<UTEModelCustomWatchServer *> *watchServerList) {
                    NSMutableArray *watchServerArr = [NSMutableArray array];
                    for (NSUInteger i = 0; i < watchServerList.count;i++) {
                        UTEModelCustomWatchServer *serverItem = [watchServerList objectAtIndex:i];
                        NSMutableDictionary *wsItem = [NSMutableDictionary dictionary];
                        [wsItem setObject:serverItem.previewBgUrl forKey:@"defaultBg"];
                        [wsItem setObject:serverItem.previewBgUrl forKey:@"defaultBgBg"];
                        [wsItem setObject:[NSString stringWithFormat:@"%ld*%ld", model.width, model.height] forKey:@"dpi"];
                        [wsItem setObject:serverItem.firmwareURL forKey:@"file"];
                        [wsItem setObject:@(serverItem.defaultWidgetPosition) forKey:@"defaultWidgetPosition"];
                        
                        NSMutableArray *positionArr = [NSMutableArray array];
                        if (serverItem.previewTimeUp.length > 0) {
                            [positionArr addObject:[NSDictionary dictionaryWithObjectsAndKeys:serverItem.previewTimeUp, @"defaultWidget", nil]];
                        }
                        if (serverItem.previewTimeDown.length > 0) {
                            [positionArr addObject:[NSDictionary dictionaryWithObjectsAndKeys:serverItem.previewTimeDown, @"defaultWidget", nil]];
                        }
                        if (serverItem.previewTimeLeft.length > 0) {
                            [positionArr addObject:[NSDictionary dictionaryWithObjectsAndKeys:serverItem.previewTimeLeft, @"defaultWidget", nil]];
                        }
                        if (serverItem.previewTimeRight.length > 0) {
                            [positionArr addObject:[NSDictionary dictionaryWithObjectsAndKeys:serverItem.previewTimeRight, @"defaultWidget", nil]];
                        }
                        
                        [wsItem setObject:positionArr forKey:@"position"];
                        
                        [watchServerArr addObject:wsItem];
                    }
                    
                    NSData *resultData = [NSJSONSerialization dataWithJSONObject:watchServerArr options:0 error:nil];
                    NSString *resultStr = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
                    result(resultStr);
                } failure:^(NSError *error) {
                    NSLog(@"%@", error);
                    result(@NO);
                }];
            }
            else {
                result(@NO);
            }
        }];
    } else if([method isEqualToString:@"getWatchFaceParams"]){
        NSLog(@"getWatchFaceParams");
        if (![self isConnected]) {
            result(@"");
            return YES;
        }
        
        [[UTEDeviceMgr sharedInstance].dial getWatchFaceParams:^(UTEModelWatchFaceParams *model, NSInteger errorCode, NSDictionary *uteDict) {
            NSLog(@"getWatchFaceParams === %ld, %ld, %ld == %@", errorCode, model.maxCapacity, model.cornerRadius, [uteDict objectForKey:@"data"]);

            NSDictionary *paramsDictionary = @{
                    @"maxWatchFaceVersion": model.maxWatchFaceVersion,
                    @"width": [NSNumber numberWithInteger:model.width],
                    @"height": [NSNumber numberWithInteger:model.height],
                    @"supportFileType": [NSNumber numberWithInteger:model.supportFileType],
                    @"earlyWatchFaceVersion": model.earlyWatchFaceVersion,
                    @"screenType": [NSNumber numberWithInteger:model.shape],
                    @"screenCorner": [NSNumber numberWithInteger:model.cornerRadius],
                    @"maxFileSize": [NSNumber numberWithInteger:model.maxCapacity],
                    @"watchFaceCount": [NSNumber numberWithInteger:model.maxCountOnline],
                    @"maxCountOffline": [NSNumber numberWithInteger:model.maxCountOffline],
            };

            NSDictionary *dataDictionary = @{
                    @"data": paramsDictionary,
            };

            NSData *resultData = [NSJSONSerialization dataWithJSONObject:dataDictionary options:0 error:nil];
            NSString *resultStr = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
            result(resultStr);
        }];
    } else if([method isEqualToString:@"uploadWatchFace"]){
        NSLog(@"uploadWatchFace");
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        NSDictionary *dictionay = [params objectForKey:KEY_VALUE];
        NSLog(@"uploadWatchFace dictionay: %@", dictionay);
        NSString *resource = [dictionay objectForKey:@"url_path"];
        NSString *path = [dictionay objectForKey:KEY_PATH];
        NSString *fileName = [NSURL URLWithString:resource].lastPathComponent;
        NSString *filePath = [[path stringByAppendingString: @"/"] stringByAppendingString:fileName];
        NSLog(@"filePath: %@", filePath);
        
        [[UTEDeviceMgr sharedInstance].dial readRestingScreenSupports:^(NSInteger max, NSInteger errorCode) {
            NSLog(@"readRestingScreenSupports max: %ld error code: %ld", max, errorCode);
        }];

        if([UTEBluetoothMgr sharedInstance].connnectModel.platform==UTEDevicePlatformTypeAC7012x) {
            [[UTEDeviceMgr sharedInstance].dial readJLWatchFaces:^(NSArray<UTEModelWatchFaceJL *> *arrayList, NSInteger errorCode) {
                NSLog(@"readJLWatchFaces ===== %ld", errorCode);
            }];
            
            UTEModelWatchFaceJL *watchFaceJL = [[UTEModelWatchFaceJL alloc] init];
            watchFaceJL.filePathOnline = filePath;
            watchFaceJL.index = 11; //当前写死，因为固件说这个
            watchFaceJL.operate = UTEWatchFaceTypeJLOperateAdd;
            watchFaceJL.category = UTEWatchFaceTypeJLCategoryOnline;
            [[UTEDeviceMgr sharedInstance].dial operateJLWatchFace:(watchFaceJL) block:^(CGFloat process, BOOL isSuccess, NSInteger errorCode) {
                NSLog(@"uploadWatchFace success ===== %ld", errorCode);
                if (errorCode == UTEDeviceErrorNil) {
                    NSLog(@"uploadWatchFace success ===== %d==%f", isSuccess, process);
                    NSMutableDictionary *eventDict = [[NSMutableDictionary alloc] initWithDictionary: @{
                        KEY_PATH: [weakSelf getPath],
                        KEY_METHOD: @"uploadWatchFace"
                    }];
                    
                    if (isSuccess) {
                        [eventDict setObject:ACTION_COMPLETE forKey:KEY_ACTION];
                        result(@YES);
                    } else {
                        [eventDict setObject:ACTION_PROGRESS forKey:KEY_ACTION];
                        [eventDict setObject:@(100) forKey:KEY_DURATION];
                        [eventDict setObject:@((int)(100 * process)) forKey:KEY_PROGRESS];
                    }
                    
                    [weakSelf.eventHander publishEvent:eventDict async:YES];
                } else {
                    NSLog(@"uploadWatchFace fail =====");
                    result(@NO);
                }
            }];
        } else {
            NSDictionary *dict = @{@"filePath":filePath};
            [[UTEDeviceMgr sharedInstance].dial uploadWatchFace:(dict) block:^(NSString *uuid, CGFloat process, BOOL isSuccess, NSInteger errorCode) {
                NSLog(@"uploadWatchFace success ===== %ld", errorCode);
                NSMutableDictionary *eventDict = [[NSMutableDictionary alloc] initWithDictionary: @{
                    KEY_PATH: [weakSelf getPath],
                    KEY_METHOD: @"uploadWatchFace"
                }];
                if (errorCode == UTEDeviceErrorNil) {
                    NSLog(@"uploadWatchFace success ===== %d==%f", isSuccess, process);
                    
                    if (isSuccess) {
                        [eventDict setObject:ACTION_COMPLETE forKey:KEY_ACTION];
                        result(@YES);
                    } else {
                        [eventDict setObject:ACTION_PROGRESS forKey:KEY_ACTION];
                        [eventDict setObject:@(100) forKey:KEY_DURATION];
                        [eventDict setObject:@((int)(100 * process)) forKey:KEY_PROGRESS];
                    }
                    
                    [weakSelf.eventHander publishEvent:eventDict async:YES];
                    
                } else {
                    [eventDict setObject:ACTION_FAILED forKey:KEY_ACTION];
                    result(@NO);
                }
                
                [weakSelf.eventHander publishEvent:eventDict async:YES];
            }];
        }
    } else if([method isEqualToString:@"applyWatchFace"]){
        NSLog(@"applyWatchFace");
        if (![self isConnected]) {
            result(@"");
            return YES;
        }
        
        NSDictionary *dictionay = [params objectForKey:KEY_VALUE];
        NSLog(@"applyWatchFace dictionay : %@", dictionay);
        NSString *dialId = [dictionay objectForKey:@"id"];
        NSString *version = [dictionay objectForKey:@"version"];
        NSNumber *operate = [dictionay objectForKey:@"operate"];

        [[UTEDeviceMgr sharedInstance].dial applyWatchFace:[dialId intValue] version:version operate:[operate intValue] block:^(UTEModelWatchFace *model, NSInteger errorCode, NSDictionary *uteDict) {
            NSLog(@"applyWatchFace ===  %@//%ld", uteDict, errorCode);
            NSString *newtApplyWatchFace = [weakSelf getNewDataString:uteDict];
            result(newtApplyWatchFace);
        }];
    } else if([method isEqualToString:@"getWatchFaceInfo"]){
        NSLog(@"getWatchFaceInfo");
        if (![self isConnected]) {
            result(@"");
            return YES;
        }
        
        [[UTEDeviceMgr sharedInstance].dial getWatchFaceInfo:(0) block:^(NSArray<UTEModelWatchFace *> *model, NSInteger errorCode, NSDictionary *uteDict) {
            NSLog(@"getWatchFaceInfo ===  %@//%ld", uteDict, errorCode);

            NSString *newtWatchFaceInfo = [weakSelf getNewDataString:uteDict];
            result(newtWatchFaceInfo);
        }];
    } else if([method isEqualToString:@"downloadImageWatchFace"]){
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        NSDictionary *dictionay = [params objectForKey:KEY_VALUE];
        NSLog(@"downloadImageWatchFace dictionay: %@", dictionay);
        NSString *imageName = [dictionay objectForKey:@"name"];
        NSString *path = [dictionay objectForKey:KEY_PATH];
        [[UTEDeviceMgr sharedInstance].dial downloadImageWatchFace:(path) imageName:(imageName) block:^(CGFloat process, BOOL isSuccess, NSInteger errorCode, NSString *filePath, NSString *imageName, NSString *uuid) {
            NSLog(@"downloadImageWatchFace success ===== %ld", errorCode);
            NSMutableDictionary *eventDict = [[NSMutableDictionary alloc] initWithDictionary: @{
                KEY_PATH: [weakSelf getPath],
                KEY_METHOD: @"downloadImageWatchFace"
            }];
            if (errorCode == UTEDeviceErrorNil) {
                NSLog(@"downloadImageWatchFace success ===== %d==%f", isSuccess, process);
                
                if (isSuccess) {
                    [eventDict setObject:ACTION_COMPLETE forKey:KEY_ACTION];
                    result(@YES);
                } else {
                    [eventDict setObject:ACTION_PROGRESS forKey:KEY_ACTION];
                    [eventDict setObject:@(100) forKey:KEY_DURATION];
                    [eventDict setObject:@((int)(100 * process)) forKey:KEY_PROGRESS];
                }
                
                [weakSelf.eventHander publishEvent:eventDict async:YES];
                
            } else {
                [eventDict setObject:ACTION_FAILED forKey:KEY_ACTION];
                result(@NO);
            }
            
            [weakSelf.eventHander publishEvent:eventDict async:YES];
        }];
    } else if([method isEqualToString:@"uploadImageWatchFace"]){
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        NSDictionary *dictionay = [params objectForKey:KEY_VALUE];
        NSLog(@"uploadImageWatchFace dictionay: %@", dictionay);
//        NSString *width = [dictionay objectForKey:@"width"];
//        NSString *height = [dictionay objectForKey:@"height"];
        NSString *path = [dictionay objectForKey:KEY_PATH];
        NSString *filePath = path;

//        UIImage *originalImage = [UIImage imageNamed:path];
//        CGSize newSize = CGSizeMake([width intValue], [height intValue]); // 新的图像尺寸
//        UIImage *resizedImage = [originalImage resizedImageWithSize:newSize];
//
//        NSString *fileName = @"resizedImage.png";
//        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//        NSString *documentsDirectory = [paths objectAtIndex:0];
//        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
//        
//        [FileUtils deleteFile: filePath];
//
//        NSData *imageData = UIImagePNGRepresentation(resizedImage); // 1.0 is the compression quality
//
//        if ([imageData writeToFile:filePath atomically:YES]) {
//            NSLog(@"Image saved to file: %@", filePath);
//        } else {
//            NSLog(@"Failed to save image to file.");
//        }

        // 现在你可以使用resizedImage变量来显示或保存新的图像
        NSDictionary *dictPath = @{@"fileName":[filePath lastPathComponent] ,@"filePath":filePath, @"index": @(0)};
        NSArray *arr = @[dictPath];

        [[UTEDeviceMgr sharedInstance].dial uploadImageWatchFace:(arr) block:^(NSString *uuid, CGFloat process, BOOL isSuccess, NSInteger errorCode) {
            NSMutableDictionary *eventDict = [[NSMutableDictionary alloc] initWithDictionary: @{
                KEY_PATH: [weakSelf getPath],
                KEY_METHOD: @"uploadImageWatchFace"
            }];
            if (errorCode == UTEDeviceErrorNil) {
                if (isSuccess) {
                    [eventDict setObject:ACTION_COMPLETE forKey:KEY_ACTION];
                    result(@YES);
                } else {
                    [eventDict setObject:ACTION_PROGRESS forKey:KEY_ACTION];
                    [eventDict setObject:@(100) forKey:KEY_DURATION];
                    [eventDict setObject:@((int)(100 * process)) forKey:KEY_PROGRESS];
                }
            } else {
                [eventDict setObject:ACTION_FAILED forKey:KEY_ACTION];
                result(@NO);
            }
            
            [weakSelf.eventHander publishEvent:eventDict async:YES];
        }];
    }

    return consumed;
}

- (NSString *) getNewDataString:(NSDictionary *) uteDict {
    id data = [uteDict objectForKey:@"data"];
    if (data == nil) {
        return @"NO";
    }
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithObject:data forKey:@"data"];
    [newDict setObject:@(YES) forKey:KEY_SUCCESS];

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:newDict options:0 error:&error];

    if(!jsonData && error) {
        return @"NO";
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return jsonString;
    }
    return @"NO";
}

@end
